﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Caching;
using GiaoTrinhEPU.Repositories.DataModels;

namespace GiaoTrinhEPU.Repositories.Repositories
{
    public class ImportRepository : BaseRepository, IImportRepository
    {
        public ImportRepository() : base() { }
        public ImportRepository(ICacheProvider cacheProvider) : base(cacheProvider) { }

        /// <summary>
        /// Clear cache of all banks
        /// </summary>
        public void ClearCache()
        {
            Cache.Invalidate("imports");
        }

        /// <summary>
        /// Clear cache of the import
        /// </summary>
        /// <param name="key"></param>
        public void ClearCache(String key)
        {
            Cache.Invalidate("import-" + key);
        }
        /// <summary>
        /// Create a new bank
        /// </summary>
        /// <param name="item"></param>
        public void CreateImport(Import item)
        {
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    db.Imports.InsertOnSubmit(item);
                    db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
        }

        // <summary>
        /// Update Import
        /// </summary>
        /// <param name="item"></param>
        public void UpdateImport(Import item)
        {
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var import = db.Imports.Single(a => a.Id.Equals(item.Id));
                    import.Id = item.Id;
                    import.IDate = item.IDate;
                    import.Quantum = item.Quantum;
                    import.WarehouseId = item.WarehouseId;
                    import.Code = item.Code;
                    import.Description = item.Description;
                    db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
        }
        /// <summary>
        /// Delete a Import
        /// </summary>
        /// <param name="id"></param>
        public void DeleteImport(int id)
        {
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var import = db.Imports.Single(a => a.Id.Equals(id));
                    db.Imports.DeleteOnSubmit(import);
                    db.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
        }
        /// <summary>
        /// List all Import in database, order by Import's name
        /// </summary>
        /// <returns></returns>
        public IEnumerable<ImportModel> ListImports(bool cacheEnabled = true)
        {
            if (cacheEnabled == true)
            {
                // if it's not in the cache, we need to read it form the repository// First, check the cache
                IEnumerable<ImportModel> importData = Cache.Get("imports") as IEnumerable<ImportModel>;

                // if it's not in the cache, we need to read it form the repository
                if (importData == null)
                {
                    //Get the repository data
                    try
                    {
                        using (var db = new ThuVienEPUDataContext())
                        {
                            db.DeferredLoadingEnabled = false;
                            importData = (from x in db.Imports
                                          join y in db.Warehouses
                                          on x.WarehouseId equals y.Id
                                          select new ImportModel
                                          {
                                              Id = x.Id,
                                              Code = x.Code,
                                              Description = x.Description,
                                              IDate =x.IDate,
                                              Quantum = x.Quantum,
                                              WarehouseName = y.Name
                                          }).OrderBy(a => a.Code).ToList();
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Writer.Write(ex.Message, ex.Source);
                    }

                    if (importData.Any())
                    {
                        Cache.Set("imports", importData, GiaoTrinhEPU.Caching.Properties.Settings.Default.CacheTime);
                    }
                }
                return importData;
            }
            else
            {
                //Get the repository data
                IEnumerable<ImportModel> importData = null;

                try
                {
                    using (var db = new ThuVienEPUDataContext())
                    {
                        importData = (from x in db.Imports
                                      join y in db.Warehouses
                                      on x.WarehouseId equals y.Id
                                      select new ImportModel
                                      {
                                          Id = x.Id,
                                          Code = x.Code,
                                          Description = x.Description,
                                          IDate = x.IDate,
                                          Quantum = x.Quantum,
                                          WarehouseName = y.Name
                                      }).OrderBy(a => a.Code).ToList();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Writer.Write(ex.Message, ex.Source);
                }

                return importData;
            }
        }
        /// <summary>
        /// Get a Import if we know it's id
        /// </summary>
        /// <param name="id">id of the banner</param>
        /// <returns>
        /// return a banner
        /// </returns>
        public Import GetImportById(int id)
        {
            Cache.Invalidate("import-" + id);
            Import importData = Cache.Get("import-" + id) as Import;
            if (importData == null)
            {
                try
                {
                    using (var db = new ThuVienEPUDataContext())
                    {
                        importData = db.Imports.Single(a => a.Id.Equals(id));
                    }
                }
                catch (Exception ex)
                {
                    Logger.Writer.Write(ex.Message, ex.Source);
                }

                if (importData != null)
                {
                    Cache.Set("import-" + id, importData, GiaoTrinhEPU.Caching.Properties.Settings.Default.CacheTime);
                }
            }
            return importData;
        }
        /// <summary>
        /// check name of the import already exist in database 
        /// </summary>
        /// <param name="name"></param>
        /// <returns>
        /// return true if exist, else false
        /// </returns>
        public bool HasNameExisted(string code)
        {
            bool isExisted = false;
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var list = (from a in db.Imports
                                where a.Code.Equals(code)
                                select a.Id).ToList();
                    isExisted = list.Count > 0;
                }
            }
            catch (Exception ex)
            {
                Logger.Writer.Write(ex.Message, ex.Source);
            }
            return isExisted;
        }

        /// <summary>
        /// check duplication of the banner in case of updating the banner
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool HasNameDuplicated(int id, string code)
        {
            bool isDuplicated = false;
            try
            {
                using (var db = new ThuVienEPUDataContext())
                {
                    var list = (from a in db.Imports
                                where a.Code.Equals(code)
                                where !a.Id.Equals(id)
                                select a.Id).ToList();
                    isDuplicated = list.Count > 0;
                }
            }
            catch (Exception ex)
            {

                Logger.Writer.Write(ex.Message, ex.Source);
            }
            return isDuplicated;
        }

    }
}
